﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace MediaInfoModelNS
{
    class MediaInfoModel
    {
        public delegate void OutputHandler(string outStr);
        public event OutputHandler outputHandler;
        
        private string mediaInfoExePath;
        private string mediaFilePath;
        private string infoType;
        
        
        private List<string> parametersList = new List<string>();
        private Dictionary<string, string> parametersDic = new Dictionary<string,string>();

        public string getParameter(string parameter) {
            return parametersDic[parameter];
        }

        public MediaInfoModel(string mediaInfoExe, string mediaFile, string infType)
        {
            mediaInfoExePath = mediaInfoExe;
            mediaFilePath = mediaFile;
            infoType = infType;
        }

        private void fillParametersDic(string resultStr) {
            char[] delimiter = { '&' };
            string[] resultsList = resultStr.Split(delimiter);
            if (resultsList.Length != parametersList.Count) {
                return;
            }
            outputHandler(String.Format("Media Information:{0}\n", infoType));
            for (int i=0; i<parametersList.Count; i++) {
                parametersDic.Add(parametersList[i], resultsList[i]);
                outputHandler(String.Format("{0}\t{1}\n", parametersList[i], resultsList[i]));
            }
            outputHandler("\n\n");
        }

        public void addParameter(string parameter) {
            parametersList.Add(parameter);
        }

        private string getArgumentString() {
            StringBuilder argSB = new StringBuilder();
            argSB.Append(@"--inform=" + infoType + ";");
            for (int i=0; i<parametersList.Count; i++) {
                if (i!=0) {
                    argSB.Append("&");
                }
                argSB.Append("%" + parametersList[i] + "%");
            }
            argSB.Append(" \"" + mediaFilePath + "\"");
            return argSB.ToString();
        }

        public void updateInfo() {
            string argumentsString = getArgumentString();
            
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = mediaInfoExePath;
            start.Arguments = argumentsString;
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            start.CreateNoWindow = true;

            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    fillParametersDic(result);
                    //Console.WriteLine(result);
                }
            }
        }
    }
}
